<?php

namespace app\common\logic;

use addons\shopro\model\Goods;
use addons\shopro\model\Order;
use addons\shopro\model\UserCoupons;
use addons\shopro\model\UserServe;
use app\common\model\User;
use think\Db;

/**
 * 会员等级
 */
class UserLevelLogic
{
    private static $levelMap = [
        [
            'id' => 0,
            'name' => '入会',
            'need_invite' => 0,
            'first_consume_users' => 0,
            'month_award_money' => 0, //月度奖励金额 单位元
        ],
        [
            'id' => 1,
            'name' => '青铜',
            'need_invite' => 5,
            'first_consume_users' => 5,
            'month_award_money' => 0, //月度奖励金额
        ],
        [
            'id' => 2,
            'name' => '白银',
            'need_invite' => 20,
            'first_consume_users' => 20,
            'month_award_money' => 0, //月度奖励金额
        ],
        [
            'id' => 3,
            'name' => '黄金',
            'need_invite' => 50,
            'first_consume_users' => 50,
            'month_award_money' => 0, //月度奖励金额
        ],
        [
            'id' => 4,
            'name' => '钻石',
            'need_invite' => 120,
            'first_consume_users' => 120,
            'month_award_money' => 0, //月度奖励金额
        ],
        [
            'id' => 5,
            'name' => '星耀',
            'need_invite' => 200,
            'first_consume_users' => 200,
            'month_award_money' => 0, //月度奖励金额
        ]
    ];

    //获取当前用户等级
    public static function getCurLevelByUserId($k)
    {
        $list = self::getLevelCfgList();
        return $list[$k] ?? [];
    }

    public static function getLevelNameById($id)
    {
        $levelList = self::getLevelCfgList();
        return $levelList[$id]['name'] ?? '';
    }

    public static function getLevelCfgList()
    {
        $res = [];
        $res[] = [
            'id' => 0,
            'name' => '入会',
            'need_invite' => 0,
            'first_consume_users' => 0,
            'month_award_money' => 0, //月度奖励金额 单位元
        ];
        $list = Db::name('user_level')->order('level_id', 'asc')->column('*');
        foreach ($list as $item) {
            $res[$item['level_id']] = [
                'id' => $item['level_id'],
                'name' => $item['level_name'],
                'need_invite' => $item['need_invite'],
                'first_consume_users' => $item['first_consume_users'],
                'month_award_money' => $item['month_award_money'],
            ];
        }
        return $res;
    }

    /*
     * 获取用户升级详情
     */
    public function getUserLevelUp($uid)
    {
        $level_data= self::getLevelCfgList();

        $userInfo = Db::name('user')->where(['id' => $uid])->field(['userinfo_complete', 'member_level','child_user_count_1'])->find();

        $returnData = [];
        if (empty($userInfo) ) {
            $returnData['need_member'] = 0;
            $returnData['next_level'] = '暂无';
            $returnData['level_name'] = '无';
            $returnData['str'] = '请先注册';
            return $returnData;
        }
        if($userInfo['member_level'] < 0) {
            $returnData['need_member'] = 0;
            $returnData['next_level'] = '暂无';
            $returnData['level_name'] = '无';
            $returnData['str'] = '完善个人信息升级为入会会员';
            return $returnData;
        }
        //首页返回
        $returnData['level_name'] =  $level_data[$userInfo['member_level']]['name'];
        if ($userInfo['member_level'] == 5) {
            $returnData['need_member'] = 0;
            $returnData['next_level'] = '暂无';
            $returnData['level_name'] = '无';
            $returnData['str'] = '当前已为最高等级';
            return $returnData;
        }
        $firstTotal = Db::name('user')->where(['parent_user_id' => $uid, 'first_consumer_status' => 1])->count();
        $member_level = $userInfo['member_level'];
        $returnData['need_member'] = $level_data[$member_level + 1]['need_invite'] - $userInfo['child_user_count_1'];
        $returnData['need_first_consume'] = $level_data[$member_level + 1]['first_consume_users'] - $firstTotal;
        $returnData['next_level'] = $level_data[$member_level + 1]['name'];
        //$returnData['str'] = '分享[' . $returnData['need_member'] . '人]入会且该' . $returnData['need_first_consume'] . '人完成首次消费升级' . $returnData['next_level'];
        $returnData['str'] = sprintf('再邀请%s人完成首次消费升级为%s',$returnData['need_first_consume'],$returnData['next_level']);
        return $returnData;
    }

    /**
     * 获取用户等级详情
     * @param int uid
     * @return int[]
     */
    public function getUserLevelDetail($uid)
    {
        $returnData['level_cfg'] = self::getLevelCfgList();
        $returnData['user_level'] = [
            'userinfo_complete' => 0,
            'invite_success' => 0,
            'first_consume_users' => 0,
            'current_level' => -1,
        ];
        $userInfo = Db::name('user')->where(['id' => $uid])->field(['userinfo_complete', 'member_level'])->find();

        if (empty($userInfo)) {
            return $returnData;
        }

        $returnData['user_level']['userinfo_complete'] = $userInfo['userinfo_complete'];
        $returnData['user_level']['current_level'] = $userInfo['member_level'];

        //当前人邀请的用户数
        $inviteTotal = Db::name('user')->where(['parent_user_id' => $uid])->count();
        $returnData['user_level']['invite_success'] = $inviteTotal;
        if (!empty($inviteTotal)) {
            $firstTotal = Db::name('user')->where(['parent_user_id' => $uid, 'first_consumer_status' => 1])->count();
            $returnData['user_level']['first_consume_users'] = $firstTotal;
        }

//        $memberLevel = -1;
//        foreach ($returnData['level_cfg'] as $v) {
//            if ($v['need_invite'] > $returnData['user_level']['invite_success'] && $v['first_consume_users'] > $returnData['user_level']['first_consume_users']) {
//                break;
//            }
//            $memberLevel = $v['id'];
//        }

//        $returnData['user_level']['current_level'] = $memberLevel;

        return $returnData;
    }

    /**
     * 支付完订单 处理支付人首次消费 处理更新邀请人等级
     * @param $payUid int 支付订单uid
     */
    public function updateUserMemberLevel($order)
    {
        $payUid = $order['user_id'] ?? 0;
        if(empty($payUid)){
            return true;
        }
        $payUserInfo = Db::name('user')->where(['id' => $payUid])->field(['first_consumer_status', 'parent_user_id'])->find();
        trace('处理支付人首次消费:'.$payUserInfo['first_consumer_status']);
        trace($order);
        if ($payUserInfo['first_consumer_status'] == 0) {
            if ($order->coupons_id) {
                $coupons = UserCoupons::get($order->coupons_id);
                $pay_fee = Order::where('order_sn', $order->order_sn)->value('pay_fee');
                if (!($coupons['coupons_id'] == 1 && $pay_fee == 29.9)) {
                    Db::name('user')->where(['id' => $payUid])->update(['first_consumer_status' => 1]);
                }
            }else{
                Db::name('user')->where(['id' => $payUid])->update(['first_consumer_status' => 1]);
            }
        }

        if (empty($payUserInfo['parent_user_id'])) {
            return true;
        }

        // 如果邀请人的个人信息未完善 则不更新
        $parentUserComplete = Db::name('user')->where(['id' => $payUserInfo['parent_user_id']])->field(['userinfo_complete', 'member_level'])->find();
        if (empty($parentUserComplete['userinfo_complete'])) {
            return true;
        }

        $inviteTotal = Db::name('user')->where(['parent_user_id' => $payUserInfo['parent_user_id']])->count();

        if (!empty($inviteTotal)) {
            $firstTotal = Db::name('user')->where(['parent_user_id' => $payUserInfo['parent_user_id'], 'first_consumer_status' => 1])->count();

            $memberLevel = -1;
            foreach (self::getLevelCfgList() as $v) {
                if ($v['need_invite'] > $inviteTotal || $v['first_consume_users'] > $firstTotal) {
                    break;
                }
                $memberLevel = $v['id'];
            }

            if ($memberLevel > $parentUserComplete['member_level']) {
                Db::name('user')->where(['id' => $payUserInfo['parent_user_id']])->update(['member_level' => $memberLevel]);
                UserServe::userLevel($payUserInfo['parent_user_id']); //发放升级权益
            }

        }
        return true;

    }

    /**
     * 获取会员等级对应的遡源系列折扣
     */
    public static function getUserMemberLevelOrderCut($uid, $goods)
    {
        try{
            $goods_id = $goods[0]['goods_id'] ?? 0;
            if(empty($goods_id)){
                trace($goods);
                return 1;
            }
            $good = Goods::where(['id' => $goods_id])->find();
            $goodCategoryArr = !empty($good['category_ids']) ? explode(',', $good['category_ids']) : [];

            if(empty($good) || !in_array(11, $goodCategoryArr)){
                trace('不属于溯源系列没有会员优惠');
                return 1;
            }

            $levelInfo = Db::name('user')->where(['id' => $uid])->value('member_level');
            switch ($levelInfo) {
                case 0:
                case 1:
                    $discount = 0.9;
                    break;
                case 2:
                case 3:
                    $discount = 0.85;
                    break;
                case 4:
                case 5:
                    $discount = 0.8;
                    break;
                default :
                    $discount = 1;
                    break;
            }
        }catch (\Throwable $e){
            trace('获取会员折扣失败'.$e->getTraceAsString(), 'debug');
            trace('rq_param:'.$uid.'_'.json_encode($goods));
            $discount = 1;
        }

        return $discount;
    }


    /**
     * 订单金额分成
     * 个护系列，以零售价的60%进入分享奖励层级
     * 颜护系列，以零售价的50%进入分享奖励层级
     * 上级奖励60%、上上级奖励30%、上上上级奖励10%
     */
    public static function divisionOrderMoney($order)
    {

        if (empty($order->item)) {
            return false;
        }
        $items = $order->item;
        $goods_ids = array_column($items, 'goods_id');
        if (empty($goods_ids[0])) {
            return false;
        }
        $goods_id = $goods_ids[0];
        $good = Goods::where(['id' => $goods_id])->find();
        if (empty($good)) {
            return false;
        }
        // 用户等级判断，发放服务礼遇
        $orderUid = $order->user_id;
        $orderId = $order->id;
        $payMoney = $order->total_fee;
        if($order['total_fee'] <= 0){
            return false;
        }

        //使用了优惠券=1的不参与分成
        if ($order->coupons_id){
            $coupons = UserCoupons::get($order->coupons_id);
            if (!empty($coupons) && $coupons['coupons_id'] == 1){
                return false;
            }

        }


        $categoryType = $good['category_ids'] ?? '';
        $categoryArr = explode(',', $categoryType);

        /**
         * 3个护 2颜护 15 16 是颜护的子分类 兼容商品只有子分类
         */
//        if (!in_array($categoryType, [2, 3])) {
//            return true;
//        }

        if(!in_array(2, $categoryArr) && !in_array(3, $categoryArr) && !in_array(12, $categoryArr) && !in_array(15, $categoryArr) && !in_array(16, $categoryArr)){
            return true;
        }

        //查询是非有邀请人
        $divisionList = [];
        //分佣比例
        $rateMap = [
            0 => 0.65,
            1 => 0.35,
            //2 => 0.1,
        ];

        for ($i = 0; $i < 2; $i++) {
            $pId = self::_getUserParentId($orderUid);
            if (empty($pId)) {
                break;
            }
            $orderUid = $pId;
            $divisionList[$pId] = $rateMap[$i];
        }

        if (empty($divisionList)) {
            trace('该笔订单不存在分佣' . $orderId);
            return true;
        }

//        if($categoryType == 3){
//            $cateRate = 0.6;
//        }else{
//            $cateRate = 0.5;
//        }

        // 3个护
        if(in_array(3, $categoryArr)){
            $cateRate = 0.6;
        }else{ //颜护存在子分类
            $cateRate = 0.5;
        }

        $divisionMoney = (($payMoney * 100) * $cateRate); //转化成分

        $data = [];
        $j = 0;
        foreach ($divisionList as $uid => $rate) {
            $j++;
            $data[$uid] = [
                'uid' => $uid,
                'order_id' => $orderId,
                'order_price' => $payMoney,
                'order_rate' => $cateRate,
                'commission_level' => $j,
                'commission_rate' => $rate,
                'commission_price' => ($divisionMoney * $rate) / 100,
                'createtime' => time(),
            ];
        }

        Db::name('shopro_commission_division_log')->insertAll($data);
        return true;
    }

    private static function _getUserParentId($uid)
    {
        $user =  Db::name('user')->where(['id' => $uid])->value('parent_user_id');
        //如果 没有上级发放给运营账户
        if(empty($user)){
            $user = User::yunyingUser();
        }
        return $user;
    }

    // 用户积分
    public static function payOrderAddScore($order)
    {
        if (empty($order)) {
            return false;
        }
        $payMoney = $order->pay_fee;
        $uid = $order->user_id;
        if (empty($payMoney) || $payMoney < 1) {
            return false;
        }
        if (empty($uid)) {
            return false;
        }
        // 用户级别获取
        $user = User::get($uid);
        $userLevel = $user->member_level ?? -1;
        $birthday = $user->birthday ?? '';
        if (empty($userLevel)) {
            return false;
        }
        $rate = 1; // 默认积分倍数
        if ($userLevel == 4) { // 钻石
            $rate = 1.2;
        } elseif ($userLevel == 5) { // 星耀
            $rate = 1.5;
        }

        // 是否是生日月，生日月加速1.5倍
        if (date('m', strtotime($birthday)) == date('m')) {
            $rate = 1.5;
        }

        // 计算积分数量
        $score = (int)bcmul(intval($payMoney), $rate);
        if ($score < 1) { // 积分不足1，不加
            return false;
        }
        // 加积分
        User::score($score, $uid, '下单消费加积分');
        return true;
    }

}
